<template>
  <div class="app-page">
    <div class="content">
      <el-table-form ref="form" :model="query">
        <el-form-item label="所属机构:" prop="orgSNNo">
          <el-tree-select
            v-model="query.orgSNNo"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
        <el-form-item :table-form-merge="0.2">
          <el-checkbox v-model="checked" style="margin-right: 20px;">包含下级</el-checkbox>
        </el-form-item>
        <el-form-item label="用户名称:" prop="userName">
          <el-input v-model.trim="query.userName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="用户编号:" prop="userCode">
          <el-input v-model.trim="query.userCode" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="类型:" prop="utype">
          <el-select v-model="query.utype" placeholder="请选择" filterable clearable>
            <el-option
              v-for="item in userTypeMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话:" prop="uphone">
          <el-input v-model.trim="query.uphone" clearable @input="query.uphone=query.uphone.replace(/[^0-9]/g,'')" />
        </el-form-item>
        <el-form-item label="账户类型" prop="accountType">
          <el-select
            v-model="query.accountType"
            clearable
            style="width: 170px; margin-right: 2px;"
          >
            <el-option label="主账户" :value="1" />
            <el-option label="子账户" :value="2" />
          </el-select>
        </el-form-item>
        <template v-slot:btns>
          <el-button v-permission="[50101,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>

      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :immediate-fetch="true"
        @fetch="fetchData"
      />
    </div>
    <login-history ref="loginHistory" />
    <reset-pwd ref="resetPwd" />
    <user-detail ref="userDetail" />
  </div>
</template>

<script>

  import { mapGetters } from 'vuex'
  import { formatColumnMap, parseTime } from '@/utils'
  import LoginHistory from './components/LoginHistory'
  import UserDetail from './components/userDetail'
  import ResetPwd from './components/ResetPwd'
  import getTreeData from '@/utils/jsonTree'
  import { getSysUserType, getUserStatus, sysQueryUserList } from '@/api'

  export default {
    name: 'distributor',
    components: {
      LoginHistory,
      ResetPwd,
      UserDetail
    },
    data() {
      return {
        treeData: [],
        userTypeMap: [],
        userStatusMap: [],
        currentOrg: null,
        checked: false,
        orgSNNo: undefined,
        orgId: undefined,
        query: {
          userName: '',
          userCode: '',
          orgSNNo: '',
          uphone: undefined,
          utype: '',
          accountType: null
        },
        tableData: {
          total: 0,
          column: [
            {
              prop: 'idx',
              label: '序号',
              width: 60
            },
            {
              prop: 'userCode',
              label: '用户编号',
              width: 110,
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openUserDetail(row)}>{ row.userCode }</el-link>
            },
            {
              prop: 'accountType',
              label: '账户类型',
              width: 120,
              render: (h, { row }) => row.accountType ? <span>{ row.accountType === 1 ? '主账户' : '子账户'}</span> : ''
            },
            {
              prop: 'subCount',
              label: '子账户数',
              width: 120
            },
            {
              prop: 'userName',
              label: '用户姓名',
              width: 110
            },
            {
              prop: 'orgName',
              label: '所属机构',
              width: 180
            },
            {
              prop: 'uTypeNames',
              label: '类型',
              width: 110,
              showOverflowTooltip: true
              // render: (h, { row }) => {
              //   if (!row.utype) return ''
              //   const arr = this.userTypeMap.filter((item, index) => (row.utype >> index) & 1)
              //   const str = arr.map(i => i.desc).join(',')
              //   return <span>{str}</span>
              // }
            },
            {
              prop: 'urole',
              width: 170,
              label: '角色'
            },
            {
              prop: 'usex',
              label: '性别',
              width: 60,
              formatter: row => {
                return row.usex
                  ? row.usex === 1 ? '男' : row.usex === 2 ? '女' : '未录入'
                  : '未录入'
              }
            },
            {
              prop: 'uphone',
              width: 110,
              label: '联系电话'
            },
            {
              prop: 'uaddress',
              width: 120,
              label: '地址'
            },
            {
              prop: 'ustatus',
              width: 120,
              label: '状态',
              render: (h, { row }) => <span>{ row.ustatus ? formatColumnMap(this.userStatusMap, 'value', row.ustatus, 'desc') : '' }</span>

            },
            {
              prop: 'lastLoginDt',
              width: 170,
              label: '最后登录时间',
              // render: (h, { row }) => <el-link underline={false} onClick={() => this.openLoginHistory(row)}>{ row.lastLoginDt && parseTime(row.lastLoginDt, '{y}-{m}-{d} {h}:{i}:{s}') }</el-link>
              render: (h, { row }) => <span>{ row.lastLoginDt && parseTime(row.lastLoginDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 100,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link v-permission={[50101, 2]} v-show={row.accountType === 1} underline={false} type='danger' size='mini' onClick={() => this.resetPwd(row, $index)}>
                      重置密码
                    </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    watch: {
      'query.orgSNNo': {
        handler(newName, oldName) {
          if (!newName) {
            this.orgId = undefined
            this.orgSNNo = undefined
          }
        },
        immediate: true
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.getUstatusData(), this.getTypeData()])
    },
    methods: {
      async fetchData({ currentPage, pageSize }) {
        const query = {
          currentPage,
          pageSize,
          ...this.query
        }
        if (this.checked) {
          query.orgSNNo = this.orgSNNo
        } else {
          query.orgSNNo = undefined
          query.orgId = this.orgId
        }
        const res = await sysQueryUserList(query)
        this.tableData.data = res.data.rows.map((item, index) => ({
          ...item,
          idx: index + ((currentPage - 1) * pageSize) + 1
        }))
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgSNNo = this.treeData[0].orgSNNo
        this.orgSNNo = this.treeData[0].orgSNNo
        this.orgId = this.treeData[0].orgId
      },
      async getTypeData() {
        const res = await getSysUserType()
        if (res && res.data) {
          this.userTypeMap = res.data
        }
      },
      async getUstatusData() {
        const res = await getUserStatus()
        if (res && res.data) {
          this.userStatusMap = res.data
        }
      },
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
        this.orgId = value.orgId
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 用户角色
      async editRole(row) {
        await this.$refs.editRole.open(row)
        this.$refs.lbTable.fetch()
      },
      // 重置密码
      async resetPwd(row) {
        await this.$refs.resetPwd.open(row)
        this.$refs.lbTable.fetch()
      },
      // del(row, index) {
      //   this.$confirm('确定删除此用户？', '提示', {
      //     type: 'warning'
      //   }).then(() => {

      //   })
      // },
      // 点击最后登陆时间打开历史登录记录
      async openLoginHistory(row) {
        await this.$refs.loginHistory.open(row)
      },
      // 展示配送员详情
      openUserDetail(row) {
        this.$refs.userDetail.open(row)
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
